<template>
    <!-- 新增客户 -->
    <div class="dialog-box">
        <el-dialog v-model="open" :title="title" width="900">
            <el-form :model="form" label-width="100px" style="margin-bottom: 50px;">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="客户" required>
                            <el-input v-model="form.name" placeholder="请选择" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="联系邮箱" required>
                            <el-input v-model="form.email" placeholder="请选择" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 两个下拉选择 -->
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="管家站" required>
                            <el-select v-model="form.shop_id" placeholder="请选择管家站">
                                <el-option v-for="item in shopList" :key="item.id" :label="item.name"
                                    :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="客户等级" required>
                            <el-select v-model="form.level_id" placeholder="请选择客户等级id">
                                <el-option v-for="item in levelList" :key="item.id" :label="item.name"
                                    :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="联系人" required>
                            <el-input   v-model="form.username" placeholder="请选择" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="联系人电话" required>
                            <el-input type="number" @input="handleInput" v-model="form.phone" placeholder="请选择" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="地区" required>
                            <el-cascader v-model="form.regionValue" :options="regionOptions" :props="cascaderProps"
                                placeholder="请选择省/市/区" style="width: 100%" @change="handleRegionChange" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="详细地址" required>
                            <el-input v-model="form.address" placeholder="请输入" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="负责人" required>
                            <el-input v-model="form.contact_name" placeholder="请选择负责人" suffix-icon="MoreFilled"
                                @focus="openPurchasingDirectorPopup" readonly />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="负责人电话" required>
                            <el-input type="number" disabled  v-model="form.contact_phone" placeholder="负责人电话" readonly />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="备注" required>
                            <el-input type="textarea" v-model="form.note" placeholder="请输入" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="open = false">取消</el-button>
                    <el-button color="#626aef" @click="handleSubmit">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <OutboundManager ref="outboundManagerRef" @selectPurchasingDirector="handleSelectPurchasingDirector" />
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import OutboundManager from "./OutboundManager.vue";
import api from "@/api";
import { regionData } from "@/utils/regionData";
import { ElMessage } from "element-plus";

const outboundManagerRef = ref<any>(null); // 选择采购负责人弹窗
const open = ref<boolean>(false); // 弹窗控制器

// 计算属性
const title = computed(() => {
    return form.id ? '编辑客户' : '新增客户';
});

const form = reactive<any>({
    id: '', // 客户id
    name: '', // 客户名称
    email: '', // 邮箱
    shop_id: '', // 管家站
    level_id: '', // 客户等级
    username: '', // 联系人
    phone: '', // 联系人电话
    regionValue: [], // 地区级联选择的值
    province: '', // 省
    city: '', // 市
    area: '', // 区
    address: '', // 详细地址
    contact_id: '', // 负责人id
    contact_name: '', // 负责人姓名
    contact_phone: '', // 负责人电话
    note: '' // 备注
});

// 地区级联选择器配置 - 处理三级数据结构
const regionOptions = ref<any[]>([]);
const cascaderProps = {
    value: 'code',
    label: 'name',
    children: 'children',  // 统一使用 children 字段
    emitPath: true,
    checkStrictly: false,
    lazy: false
};

// 数据转换函数 - 将你的数据结构转换为级联选择器需要的格式
const transformRegionData = (data: any) => {
    return data.map((province: any) => ({
        code: province.code,
        name: province.name,
        children: province.city ? province.city.map((city: any) => ({
            code: city.code,
            name: city.name,
            children: city.children ? city.children.map((area: any) => ({
                code: area.code,
                name: area.name
            })) : []
        })) : []
    }));
};

const handleInput = (e: any) => {
 
    if(e.length > 11){
      form.phone = e.slice(0, 11);
    }
}
const handleInput2 = (e: any) => {
    if(e.length > 11){
      form.contact_phone = e.slice(0, 11);
    }
}
// 处理地区选择
const handleRegionChange = (selectedValues: string[]) => {
    console.log('选择的地区代码:', selectedValues);

    // 清空之前的选择
    form.province = '';
    form.city = '';
    form.area = '';

    if (!selectedValues || selectedValues.length === 0) {
        console.log('清空地区选择');
        return;
    }

    // 根据选择的代码查找对应的名称
    if (selectedValues.length >= 1) {
        // 查找省份
        const province = regionOptions.value.find((p: any) => p.code === selectedValues[0]);
        if (province) {
            form.province = province.name;
            console.log('选择的省份:', form.province);

            // 查找城市
            if (selectedValues.length >= 2 && province.children) {
                const city = province.children.find((c: any) => c.code === selectedValues[1]);
                if (city) {
                    form.city = city.name;
                    console.log('选择的城市:', form.city);

                    // 查找区县
                    if (selectedValues.length >= 3 && city.children) {
                        const area = city.children.find((a: any) => a.code === selectedValues[2]);
                        if (area) {
                            form.area = area.name;
                            console.log('选择的区县:', form.area);
                        }
                    }
                }
            }
        }
    }

    console.log('最终地区信息:', {
        province: form.province,
        city: form.city,
        area: form.area,
        codes: selectedValues
    });
};

// 根据省市区名称反向查找对应的code值
const findRegionCodes = (provinceName: string, cityName: string, areaName: string) => {
    const codes: string[] = [];
    
    // 查找省份
    const province = regionOptions.value.find((p: any) => p.name === provinceName);
    if (province) {
        codes.push(province.code);
        
        // 查找城市
        if (province.children) {
            const city = province.children.find((c: any) => c.name === cityName);
            if (city) {
                codes.push(city.code);
                
                // 查找区县
                if (city.children) {
                    const area = city.children.find((a: any) => a.name === areaName);
                    if (area) {
                        codes.push(area.code);
                    }
                }
            }
        }
    }
    
    return codes;
};

const openLoadings = (item?: any) => {
    console.log('item', item);

    open.value = true;
    
    // 先转换地区数据格式
    regionOptions.value = transformRegionData(regionData);
    console.log('转换后的地区数据:', regionOptions.value);
    
    if (item && item.id) {
        // 编辑模式 - 填充表单数据
        Object.assign(form, item);
        
        // 如果有地区信息，根据省市区名称查找对应的code
        if (item.province && item.city && item.area) {
            const codes = findRegionCodes(item.province, item.city, item.area);
            form.regionValue = codes;
            
            console.log('编辑模式 - 地区信息:', {
                province: item.province,
                city: item.city,
                area: item.area,
                codes: codes
            });
        } else {
            form.regionValue = [];
        }
    } else {
        // 新增模式 - 重置表单
        Object.assign(form, {
            id: '',
            name: '',
            email: '',
            shop_id: '',
            level_id: '',
            username: '',
            phone: '',
            regionValue: [],
            province: '',
            city: '',
            area: '',
            address: '',
            contact_id: '',
            contact_name: '',
            contact_phone: '',
            note: ''
        });
    }

    console.log('级联配置:', cascaderProps);

    getShopList();
    getLevelList();
};

const shopList = ref<any[]>([]);
// 获取管家站列表
const getShopList = async () => {
    try {
        const res = await api.publicFun.getShopList();
        if (res.code == 200) {
            shopList.value = res.data;
        }
    } catch (error) {
        console.error('获取管家站列表失败:', error);
    }
}

// 获取客户等级列表
const levelList = ref<any[]>([]);
const getLevelList = async () => {
    try {
        const res = await api.publicFun.getLevelList();
        if (res.code == 200) {
            levelList.value = res.data;
        }
    } catch (error) {
        console.error('获取客户等级列表失败:', error);
    }
}

// 选择负责人
const openPurchasingDirectorPopup = (e: any) => {
    outboundManagerRef.value.openLoading();
    e.target.blur();
};

const emit = defineEmits(["init"]); // 触发父组件的初始化方法

const handleSubmit = async () => {
    console.log("提交表单数据:", form);

    // 验证必填项
    if (!form.name || !form.email || !form.contact_name) {
        ElMessage.error('请填写完整的客户信息');
        return;
    }

    try {
        // 构建提交数据
        const submitData = {
            ...form,
            // 移除级联选择器的值，因为已经转换成具体的省市区名称
            regionValue: undefined
        };

        console.log("最终提交数据:", submitData);
        
        if (form.id) {
            // 更新
            const res = await api.Outbound.editoutbound({ ...submitData, id: form.id });
            if (res.code == 200) {
                ElMessage.success("更新成功");
                emit("init");
                open.value = false;
            }
        } else {
            // 新增
            const res = await api.Outbound.addoutbound({ ...submitData });
            if (res.code == 200) {
                ElMessage.success("新增成功");
                emit("init");
                open.value = false;
            }
        }
    } catch (error) {
        console.error('提交失败:', error);
        ElMessage.error('操作失败，请重试');
    }
};

interface PurchasingDirector {
    id: number;
    name: string;
    mobile: string;
}

// 处理选择采购负责人
const handleSelectPurchasingDirector = (purchasingDirector: PurchasingDirector) => {
    console.log("选择的负责人:", purchasingDirector);
    form.contact_id = purchasingDirector.id; 
    form.contact_phone = purchasingDirector.mobile; 
    form.contact_name = purchasingDirector.name; 
};

defineExpose({
    openLoadings,
});
</script>



<style lang="scss" scoped>
::v-deep .el-dialog {
    --el-dialog-padding-primary: 0px;
}

::v-deep .el-dialog__header {
    padding: 10px 16px;
    border-bottom: 1px solid #f0f0f0;
    font-weight: bold;
}

::v-deep .dialog-footer {
    padding: 10px 16px;
    border-top: 1px solid #f0f0f0;
}

::v-deep .el-dialog__headerbtn .el-dialog__close {
    color: #000;
}

::v-deep .el-dialog__body {
    padding: 10px 10px;
}

:deep(.el-form-item__label) {
    justify-content: flex-start;
}

:deep(.el-form-item) {
    flex-direction: column;
    margin-bottom: 7px;
}

:deep(.el-select__wrapper) {
    background: #fafcfb;
}

:deep(.el-badge__content.is-fixed) {
    color: #666;
    border-radius: 3px;
    padding: 4px;
}

:deep(.el-table .cell) {
    display: flex;
    justify-content: center;
}

:deep(.el-button:hover) {
    color: #6860ff;
    background: #f4f5f7;
}

:deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper) {
    width: 100%;
}

:deep(.el-input__wrapper:hover) {
    box-shadow: inset 0 0 0 1px #6860ff;
}

.supply-products {
    margin-top: 20px;

    .title {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 10px;
        font-weight: bold;

        .title-text {
            display: flex;
            align-items: center;

            .line {
                height: 17px;
                width: 2px;
                border-radius: 12px;
                margin-right: 8px;
                background-color: #6860ff;
            }
        }
    }
}

.image-list {
    display: flex;
    gap: 8px;

    .el-image {
        width: 40px;
        height: 40px;
        border-radius: 4px;
    }
}
</style>